/* Copyright 2013 David Wolverton
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sbbs.base.dao;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import static java.lang.reflect.Array.newInstance;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.beanutils.ConvertUtilsBean2;
import org.hibernate.Session;
import org.hibernate.internal.SessionFactoryImpl;
import org.sbbs.genericdao.dao.jpa.GenericDAOImpl;
import org.sbbs.genericdao.search.MetadataUtil;
import org.sbbs.genericdao.search.jpa.JPAAnnotationMetadataUtil;
import org.sbbs.genericdao.search.jpa.JPASearchProcessor;


public class BaseDAOImpl<T, ID extends Serializable> extends GenericDAOImpl<T, ID> {

    @PersistenceContext(unitName = "DEFAULT")
    private EntityManager em;

    @PostConstruct
    public void init() {
        super.setEntityManager(em);
        MetadataUtil hmt = new JPAAnnotationMetadataUtil();
        JPASearchProcessor searchProcessor = new JPASearchProcessor(hmt);
        super.setSearchProcessor(searchProcessor);
    }
    
    /**
     *
     * @param id
     * @return
     */
    public boolean exist(ID id) {
        return this._exists(persistentClass, id);
    }

    /**
     *
     * @param list
     */
    public void remove(List<T> list) {
        if (list.size() > 0) {
            T[] array = (T[]) newInstance(this.persistentClass, list.size());
            list.toArray(array);
            this.remove(array);
        }
    }

    public int batchUpdate(final String ql, final Object... params) {

        Query query = this.em().createQuery(ql);
        setParameters(query, params);

        return query.executeUpdate();
    }

    /**
     * 按顺序设置Query参数
     *
     * @param query
     * @param params
     */
    public void setParameters(Query query, Object[] params) {
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i + 1, params[i]);
            }
        }
    }

    /**
     *
     * @param id
     * @return
     */
    public T findByStringId(String id) {
        ConvertUtilsBean2 cub2 = new ConvertUtilsBean2();
        this.getMetadataUtil().get(persistentClass).getIdType().getJavaClass();
        ID oid = (ID) cub2.convert(id, this.getMetadataUtil().get(persistentClass).getIdType().getJavaClass());
        return this.find(oid);
    }

    public EntityManager getEm() {
        return this.em();
    }

    protected Session getHibernateSession() {
        return this.getEm().unwrap(org.hibernate.Session.class);
    }

    protected Connection getConnection() throws SQLException {
        Session session = this.getEm().unwrap(org.hibernate.Session.class);
        SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
        Connection conn = sessionFactory.getConnectionProvider().getConnection();
        return conn;
    }

//    @Override
//    public boolean isProcExist(String procName) {
//        String sql = "SELECT count(1)   FROM USER_SOURCE  WHERE TYPE = 'PROCEDURE'    and name =?";
//        Query q = this.em().createNativeQuery(sql);
//        q.setParameter(1, procName.toUpperCase());
//        BigDecimal c = (BigDecimal) q.getSingleResult();
//        return c.intValue() > 0;
//    }
    
    
     public byte[] blobToBytes(Blob blob) {
        InputStream is = null;
        byte[] b = null;
        try {
            is = blob.getBinaryStream();
            b = new byte[(int) blob.length()];
            is.read(b);
            return b;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                is = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return b;
    }
}
